<template>
	<div class="config-manage-box">
		<!-- 算法顶部 -->
		<cameras-ai-header
			v-bind="propsState"
			:no-infrared-camera="noInfraredCamera"
			@on-add-area="areaAdd"
			@on-delete-area="areaDel"
			@on-change-area="areaChange"
			@on-copy="topControlsState.copyAllRegionVisible = true"
		></cameras-ai-header>

		<div class="config-manage-main">
			<div class="config-manage-main-tree">
				<cameras-ai-tree
					ref="camerasAiTreeRef"
					:device-tree-key="cameraInfoState.deviceTreeKey"
					@device-change="changeCamera"
				></cameras-ai-tree>
			</div>

			<!-- 算法核心部分  算法服务+视频-->
			<div class="config-manage-main-core">
				<!-- 算法服务 -->
				<div class="config-manage-main-ai-server-list">
					<cameras-ai-server-list
						v-bind="propsState"
						:no-infrared-camera="noInfraredCamera"
						@on-checked="changeChecked"
						@on-open="openServiceModal"
					></cameras-ai-server-list>
				</div>

				<!-- 视频 -->
				<div class="config-manage-main-video" tabindex="0" @keydown.delete="delGraph">
					<div class="config-manage-main-video-top">
						<cameras-ai-video-top
							ref="aiVideo"
							v-bind="propsState"
							@on-del="delGraph"
							@on-clear="handleClearCanvas"
							@on-save="handleSubmit"
							@on-switch="SwitchCheckedChange"
							@on-select="SelectCheckedChange"
						></cameras-ai-video-top>
					</div>
					<div class="config-manage-main-video-main">
						<div v-if="pageControlState.isCavansShow" class="draw-container" @click="checkAiSelected">
							<canvas id="canvas" class="canvas" style="position: absolute; z-index: 0"></canvas>
							<video
								id="cameraVideo"
								:key="cameraInfoState.cameraId"
								muted
								autoplay
								:class="[inOrOutNetwork === '0' ? 'video-srs' : 'video-zlm']"
							></video>
							<div v-if="!pageControlState.isLoadVideoSuccess || videoLoading" class="video-empty">
								<a-spin :spinning="videoLoading"></a-spin>
								<div v-if="!videoLoading" class="video-play-error">
									<global-svg-icon icon-name="video-error" width="48px" height="48px" class-name="status-icon "></global-svg-icon>
									<span>设备连接失败</span>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<service-form-modal v-bind="propsState" @close="topControlsState.serviceModalVisible = false" @ok="serviceModalOk"></service-form-modal>
		<!-- 复制全部算法配置到... -->
		<copy-all-algorithms
			v-if="topControlsState.copyAllRegionVisible"
			:visible="topControlsState.copyAllRegionVisible"
			:camera-info-state="cameraInfoState"
			@close="topControlsState.copyAllRegionVisible = false"
		></copy-all-algorithms>

		<global-confirm
			v-model:open="confirmState.confirmOpen"
			@cancel="confirmHandel(0)"
			@no-save="confirmHandel(1)"
			@save="confirmHandel(2)"
		></global-confirm>
	</div>
</template>

<script setup lang="ts" name="cameras-algorithm">
import { g6DeepClone } from 'glasssix-utils-ts';
import { videoPlay } from '@/global-utils/viedeo.utils';
import { useCanvasDraw } from '../../hooks';
import { deepEqual } from '@/global-utils/base.utils';
import { useDeleteModal } from '@/global-hooks/base.hooks';
import {
	ServiceFormModal,
	CopyAllAlgorithms,
	CamerasAiTree,
	CamerasAiHeader,
	CamerasAiServerList,
	CamerasAiVideoTop
} from '../../components/index';
import { AIConfigurationAPI } from '../../api';
import { realVideoApi } from '../../../monitoring-center/api';
import { appStore } from '@/global-store/index';
import type { AiServiceListItem, CameraInfoState, ServeState, AreaState, PageControlState } from '../../type';

const { WebSocketStore } = appStore;
const { SocketState, ScoketSend } = WebSocketStore;

const router = useRouter();
const route = useRoute();
const token = window.sessionStorage.getItem('token');

const { setOpenDeleteModal } = useDeleteModal(); // 警告弹窗
const $message: any = inject('$message');
const inOrOutNetwork = localStorage.getItem('inOrOutNetwork'); // 视频播放器类型
let cacheData = reactive<any>({}); // 缓存数据
const aiVideo = ref();
// 页面操作控制字段
const pageControlState = reactive<PageControlState>({
	switchCheckedDisabled: false, //全屏按钮禁用
	isLoadVideoSuccess: false, //视频加载成功标识
	saveBtnLoading: false, // 保存按钮loading
	videoDrawSwitch: false, // 视频绘制开关 全屏｜自定义
	OfflineStatus: true, // 当前设备是否离线 离线true 在线false
	isCavansShow: true, // 画布是否显示
	hasAlgoAuth: true, //当前算法是否授权
	isEdit: false // 页面是否有修改
});

const noInfraredCamera = ref(true);

/**
 * =============================================-- 全局通用 =============================================
 */

/**
 * 数据比对
 * @return  true 代表未改 false 代表值被更改
 * @isOut  是否是退出表单或页面
 * @callback  ok 的回调函数
 */
const pageDataCompare = (): boolean => {
	// 视频没播放成功 直接放走
	if (!pageControlState.isLoadVideoSuccess) {
		return true;
	}
	let data = {
		...g6DeepClone(areaState.areaInfo),
		// 识别区域坐标
		customizeDrawAreaCoordinates: getCoordinateValue(),
		deviceAreaAIServiceList: serveState.serviceList,
		smartUniverse:
			pageControlState.videoDrawSwitch === true ? 1 : pageControlState.videoDrawSwitch === false ? 0 : pageControlState.videoDrawSwitch
	};

	if (deepEqual(cacheData, data, [])) {
		return true;
	}

	confirmState.confirmOpen = true;

	return false;
};

/**
 * 绘制操作 当为全屏 并且视频播放成功 执行视频绘制操作
 *
 */
const videoDrawControl = () => {
	if (pageControlState.videoDrawSwitch === false && pageControlState.isLoadVideoSuccess) {
		canvasState.drawType === 2 ? drawLine() : drawPolygon();
	}
};

/**
 * 警告弹窗
 */
const useConfirmModal = () => {
	interface ConfirmState {
		confirmOpen: boolean;
		text: string;
		saveFun: Function;
	}
	const confirmState = reactive<ConfirmState>({
		confirmOpen: false,
		text: '信息尚未保存，是否确认保存信息后再离开？',
		saveFun: () => {
			console.log('保存');
		} //弹窗处理类型
	});

	/**
	 * 警告弹窗操作
	 * @param type 0 点击取消 1 不保存 2 保存
	 */
	const confirmHandel = async (type: number) => {
		// 确认
		const save = async () => {
			let status = await handleSubmit();
			if (status === 'succeed') {
				confirmState.saveFun();
			}
			cameraCancelChange();
		};
		switch (type) {
			case 1:
				confirmState.saveFun();
				cameraCancelChange();
				break;
			case 2:
				save();
				break;
			default:
				cameraCancelChange();
				break;
		}
		confirmState.confirmOpen = false;
	};

	return {
		confirmState,
		confirmHandel
	};
};

const { confirmState, confirmHandel } = useConfirmModal();

/**
 * =============================================全局通用 END =============================================
 */

/**
 * ============================================ 绘制 =============================================
 */
const {
	fullRect,
	getCoordinateValue,
	stopDraw,
	canvasState,
	drawLine,
	drawPolygon,
	initCanvas,
	drawVideo,
	handleClearCanvas,
	drawDefaultArea,
	clearCanvas,
	delGraph,
	destroy
} = useCanvasDraw();

/**
 * =============================================绘制结束 =============================================
 */
/**
 * ============================================= 加载视频 =============================================
 */

const useVideo = () => {
	// 视频loading
	const videoLoading = ref(false);
	let timer: any;
	// 视频加载成功标识
	let play: any = null;
	// 绘制区域视频
	const drawAreaVideo = () => {
		if (areaState.areaInfo) {
			if (pageControlState.videoDrawSwitch === true) {
				return fullRect();
			}
			areaState.areaInfo?.customizeDrawAreaCoordinates && drawDefaultArea(areaState.areaInfo.customizeDrawAreaCoordinates);
		}
	};
	// 绘制
	const draw = () => {
		clearTimeout(timer);
		pageControlState.isLoadVideoSuccess = true;
		videoLoading.value = false;
		const video = canvasState.video as HTMLVideoElement;
		const canvas = canvasState.canvas as fabric.Canvas;
		video.width = video.videoWidth || 1920;
		video.height = video.videoHeight || 1080;
		canvasState.scale = Math.min(canvas.getWidth() / video.width, canvas.getHeight() / video.height);

		drawVideo();
		clearCanvas();
		drawAreaVideo();
	};

	// 视频超时
	const videoOvertime = () => {
		timer && clearTimeout(timer);
		timer = setTimeout(() => {
			videoLoading.value = false;
			pageControlState.isLoadVideoSuccess = false;
			// message.error('设备连接失败');
			clearTimeout(timer);
		}, 1000 * 10);
	};

	const loadVideo = async (): Promise<void> => {
		videoLoading.value = true;
		pageControlState.isLoadVideoSuccess = false;
		if (play) {
			play.pause();
			play.stop();
			play.close();
			play = null;
			await nextTick();
		}
		canvasState.video = document.getElementById('cameraVideo') as HTMLVideoElement;
		// 视频播放
		videoPlay({ videoDomId: 'cameraVideo', videoUrl: cameraInfoState.url }, (player: any, videoStatus: number) => {
			if (!play) {
				play = player;
				videoOvertime();
			}
			if (videoStatus === 1) {
				draw();
			} else if (videoStatus === 2) {
				videoLoading.value = false;
				pageControlState.isLoadVideoSuccess = false;
			}
		});
	};

	/**
	 * 摄像头推流
	 * @param ids 需要推送或关闭的id
	 * @param isClose 是否是关流
	 */
	const videoStatus = async (ids: number, isClose: boolean = false) => {
		if (!isClose) {
			// +++通过ids更新/摄像头推流
			await realVideoApi.getPlay([ids]);
		} else {
			// 摄像头关流
			await realVideoApi.getClose([ids]);
		}
	};

	const checkAiSelected = () => {
		let flag = serveState.serviceList.some((item) => item.selected === 1);
		if (!flag) {
			$message.warning('请先选择算法');
		}
	};

	return {
		loadVideo,
		drawAreaVideo,
		videoStatus,
		checkAiSelected,
		videoLoading,
		play,
		timer
	};
};
const { loadVideo, videoLoading, drawAreaVideo, play, timer, videoStatus, checkAiSelected } = useVideo();

/**
 * ============================================= 加载视频结束 =============================================
 */

/**
 * ============================================= 区域 =============================================
 */

const useArea = () => {
	const areaState = reactive<AreaState>({
		areaInfo: {}, // 获取识别区域下的信息
		areaId: undefined, //当前区域id
		areaList: [], //区域列表
		areaAiNum: 0 //当前区域下的算法配置数量
	});
	/**
	 * 查询区域数量列表
	 */
	const getAreaList = async (id?: number | null): Promise<void> => {
		try {
			areaState.areaList = [];
			areaState.areaId = undefined;
			let { data } = await AIConfigurationAPI.getAreaList({
				deviceId: cameraInfoState.id,
				boxSerial: cameraInfoState.boxSerial
			});

			if (data) {
				areaState.areaList = data;
				areaState.areaId = id ? id : data[0];
			}
		} catch (error) {
			console.log(error);
		}
	};

	// 添加区域
	const areaAdd = async () => {
		try {
			const toNext = async () => {
				let res = await AIConfigurationAPI.addArea({
					deviceId: cameraInfoState.id,
					boxSerial: cameraInfoState.boxSerial
				});
				if (res.code === 0) {
					$message.success('添加成功');
					await getAreaList();
					areaState.areaId = areaState.areaList[areaState.areaList.length - 1];

					getByAreaInfoList();
				}
			};
			if (pageDataCompare()) {
				toNext();
			} else {
				confirmState.saveFun = toNext;
			}
		} catch (error) {
			console.log(error);
		}
	};
	// 删除区域
	const areaDel = async (id: number, index: number) => {
		try {
			const ok = async () => {
				let res = await AIConfigurationAPI.delArea({
					id,
					boxSerial: cameraInfoState.boxSerial
				});
				if (res.code === 0) {
					$message.success('删除成功');
					getAreaList(id === areaState.areaId ? null : areaState.areaId);
				}
			};
			const restartModalInfo = {
				title: `确定删除识别区域${index + 1}?`,
				okText: '确认',
				cancelText: '取消'
			};
			setOpenDeleteModal(ok, restartModalInfo);
		} catch (error) {
			console.log(error);
		}
	};
	// 区域改变
	const areaChange = async (id: number) => {
		aiVideo.value.personValue = null;
		const toNext = async () => {
			areaState.areaId = id;
			getByAreaInfoList();
			await clearCanvas();
			await drawAreaVideo();
		};

		if (pageDataCompare()) {
			toNext();
		} else {
			confirmState.saveFun = toNext;
		}
	};
	return {
		areaAdd,
		areaDel,
		areaChange,
		getAreaList,
		areaState
	};
};

const { areaAdd, areaDel, areaChange, getAreaList, areaState } = useArea();

/**
 * ============================================= 区域 END=============================================
 */

/**
 * ============================================= 绘制信息及AI服务列表 =============================================
 */
const usePageRequest = () => {
	const getByAreaInfo = async (): Promise<void> => {
		try {
			if (!areaState.areaId) {
				return;
			}
			let res: TsRes = await AIConfigurationAPI.getAreaAIList({
				id: areaState.areaId,
				boxSerial: cameraInfoState.boxSerial
			});
			if (res.code === 0) {
				areaState.areaInfo = res.data;
				aiVideo.value.personValue = res.data.zeloUserId;
				Object.assign(cacheData, g6DeepClone(res.data)); //缓存数据

				if (canvasState.drawType !== 2) {
					pageControlState.videoDrawSwitch = !!res.data?.smartUniverse;
				}

				checkedHandel();
				await clearCanvas();
				await drawAreaVideo();
			}
		} catch (error) {
			console.log(error);
		}
	};

	/**
 * 获取AI服务列表

 */
	const getByAreaInfoList = async (): Promise<void> => {
		try {
			if (!areaState.areaId) {
				return;
			}
			let res: TsRes = await AIConfigurationAPI.getAreaAIList({
				id: areaState.areaId,
				boxSerial: cameraInfoState.boxSerial
			});
			if (res.code === -17) {
				pageControlState.hasAlgoAuth = false;
				return;
			}
			if (res.code !== 0) {
				$message.error(res.message);
				return;
			}
			if (res.code === 0) {
				pageControlState.hasAlgoAuth = true;
				serveState.serviceList = (res.data.deviceAreaAIServiceList as AiServiceListItem[]).sort((a, b) => b.selected - a.selected);

				if (!noInfraredCamera.value) {
					serveState.serviceList = [{ aiSrvName: '温度检测', id: 100, selected: 1, selectable: 0 }, ...serveState.serviceList];
				}

				getByAreaInfo();

				if (serveState.serviceList.find((item: AiServiceListItem) => item.aiSrvType === 21)?.selected) {
					pageControlState.videoDrawSwitch = false;
					pageControlState.switchCheckedDisabled = true;
				}

				// 绘制类型
				let listItem = serveState.serviceList[0];

				canvasState.drawType = listItem.aiSrvDrawType;
				serveState.serviceType = listItem.aiSrvType;
				serveState.serviceName = listItem.aiSrvName;
			}
		} catch (error) {
			console.log(error);
		}
	};

	return {
		getByAreaInfo,
		getByAreaInfoList
	};
};
const { getByAreaInfo, getByAreaInfoList } = usePageRequest();

/**
 * ============================================= 绘制信息及AI服务列表结束 =============================================
 */
/**
 * ============================================= 视频顶部操作  =============================================
 */
const personValue = ref('');
const SelectCheckedChange = (data: string) => {
	personValue.value = data;
	pageControlState.isEdit = true;
};
const useTopControls = () => {
	// 顶部操作 变量
	const topControlsState = reactive({
		serviceModalVisible: false, // 配置表单弹窗显隐
		copyAllRegionVisible: false // 复制到区域的弹窗显隐
	});
	// 视频全屏 全屏 自定义切换按钮
	const SwitchCheckedChange = async (checked: boolean): Promise<void> => {
		try {
			pageControlState.isEdit = true;
			if (canvasState.drawType === 2 && checked) {
				$message.warning('越界检测无法全屏检测');
			}
			pageControlState.videoDrawSwitch = checked;
			await clearCanvas();
			await stopDraw();
			canvasState.drawType === 2 ? drawLine() : drawPolygon();
			checked && fullRect();
		} catch (error) {
			console.log(error);
		}
	};

	return {
		SwitchCheckedChange,
		topControlsState
	};
};

const { SwitchCheckedChange, topControlsState } = useTopControls();

/**
 * ============================================= 视频顶部操作 结束 =============================================
 */

/**
 * ============================================= AI服务列表 =============================================
 */

const useAiServerList = () => {
	const serveState = reactive<ServeState>({
		serviceId: null,
		serviceList: [], // AI服务列表
		serviceType: 0, // 切换算法——算法服务类型id
		serviceName: '' // 切换算法——算法服务名称
	});

	// 选中处理
	const checkedHandel = (isClick?: boolean) => {
		// 是否有选中
		const selectedNum = serveState.serviceList.filter((item) => item.selected === 1).length;
		if (selectedNum < 1) {
			pageControlState.videoDrawSwitch = -1;
			serveState.serviceList.forEach((item) => {
				item.selectable = 1;
			});
			clearCanvas();
			stopDraw();
			return true;
		}
		// 点击选中的第一个 默认全屏绘制
		if (isClick && selectedNum === 1) {
			pageControlState.videoDrawSwitch = isClick ? true : !!areaState.areaInfo.smartUniverse;
			clearCanvas();
			drawAreaVideo();
		}
	};
	// 服务开关切换
	const changeChecked = async (checked: boolean, aiItemInfo: AiServiceListItem): Promise<void> => {
		aiItemInfo.selected = checked ? 1 : 0;
		canvasState.drawType = aiItemInfo.aiSrvDrawType;
		pageControlState.isEdit = true;

		// 如果是取消选中 并且没有任何选中 就return；
		if (checkedHandel(true)) {
			return;
		}
		if ((aiItemInfo.aiSrvType === 21 && !!aiItemInfo.selected) || aiItemInfo.aiSrvDrawType === 2) {
			pageControlState.videoDrawSwitch = false;
			pageControlState.switchCheckedDisabled = true;
			clearCanvas();
			stopDraw();
			drawLine();
		} else {
			pageControlState.switchCheckedDisabled = false;
		}
		serveState.serviceList.forEach((item) => {
			if (item.aiSrvDrawType === aiItemInfo.aiSrvDrawType) {
				item.selectable = 1;
			} else {
				item.selectable = 0;
				item.selected = 0;
			}
		});
	};

	/**
	 * 配置表单弹窗
	 */
	const openServiceModal = async (item: AiServiceListItem): Promise<void> => {
		console.log(item, '111');

		serveState.serviceId = item.id;
		serveState.serviceName = item.aiSrvName;
		topControlsState.serviceModalVisible = true;
	};
	return {
		changeChecked,
		checkedHandel,
		serveState,
		openServiceModal
	};
};

const { changeChecked, checkedHandel, serveState, openServiceModal } = useAiServerList();
/**
 * ============================================= AI服务列表结束 =============================================
 */

/**
 * ============================================= 摄像头 =============================================
 *
 */

// 摄像头信息
const cameraInfoState = reactive<CameraInfoState>({
	boxSerial: '',
	id: '',
	cameraId: '',
	status: '',
	name: '',
	url: '',
	deviceTreeKey: '',
	aiSrvCountV2: 0
});
// 缓存摄像头数据
const cacheCameraInfoState = {};
// 树Ref
const camerasAiTreeRef = ref();

//  树取消操作
const cameraCancelChange = () => {
	let deviceTreeKey = cameraInfoState.deviceTreeKey;
	cameraInfoState.deviceTreeKey = '';
	nextTick(() => {
		cameraInfoState.deviceTreeKey = deviceTreeKey;
	});
};
// 摄像头切换
const toNextDevice = async (cameraInfo: CameraInfoState) => {
	console.log('摄像头切换', cameraInfo.deviceTreeKey);

	try {
		let data = {
			cameraId: cameraInfo.deviceTreeKey,
			cameraType: cameraInfo.deviceType
		};
		if (cameraInfo.deviceType === 2) {
			noInfraredCamera.value = false;
		}
		areaState.areaAiNum = cameraInfo.aiSrvCountV2;
		router.replace({ query: data }); // 更新路由设备id
		pageControlState.isCavansShow = false;
		await nextTick(); // 必须放在这里 等视图更新
		pageControlState.isCavansShow = true;
		await destroy();
		await clearCanvas();
		await stopDraw();
		serveState.serviceList = [];
		videoStatus(Number(cameraInfo.cameraId));
		Object.assign(cameraInfoState, cameraInfo);
		// 在离线状态
		pageControlState.OfflineStatus = cameraInfoState.status === 0 ? true : false;
		pageControlState.isEdit = false;
		canvasState.isClearnCanvas = false;
		await getAreaList(cameraInfo.deviceTreeKey === route.query.cameraId ? areaState.areaId : null);
		await getByAreaInfoList();
		await initCanvas(); // 初始化
		loadVideo();
		videoDrawControl();
	} catch (error) {
		console.log(error);
	}
};
const changeCamera = async (cameraInfo: Record<string, any>, isMounted: boolean = false) => {
	if (isMounted) {
		toNextDevice(cameraInfo);
		return;
	}
	Object.assign(cacheCameraInfoState, { ...g6DeepClone(cameraInfo) });

	if (pageDataCompare()) {
		toNextDevice(cameraInfo);
	} else {
		confirmState.saveFun = () => toNextDevice(cameraInfo);
	}
};

/**
 * ============================================= 保存 =============================================
 */

const useSave = () => {
	// ai算法保存
	const handleSubmit = async (): Promise<void | string> => {
		try {
			if (pageControlState.videoDrawSwitch === false) {
				pageControlState.saveBtnLoading = true;
				if (canvasState?.canvas?.getObjects().length === 0) {
					$message.error('算法配置未绘制区域');
					pageControlState.saveBtnLoading = false;
					return 'error';
				}
			}
			const params = {
				// 设备id
				activeAreaAISrvCount: areaState.areaInfo.activeAreaAISrvCount,
				areaConfigCopyable: areaState.areaInfo.areaConfigCopyable,
				boxSerial: areaState.areaInfo.boxSerial,
				id: areaState.areaInfo.id,
				deviceId: cameraInfoState.id,
				maskingAreaSize: {
					width: canvasState?.video?.width || 0,
					height: canvasState.video?.height || 0
				},
				smartUniverse:
					pageControlState.videoDrawSwitch === true ? 1 : pageControlState.videoDrawSwitch === false ? 0 : pageControlState.videoDrawSwitch,
				// 识别区域坐标
				customizeDrawAreaCoordinates: getCoordinateValue(),
				deviceAIServiceList: serveState.serviceList,
				zeloUserId: personValue.value
			};
			let res: TsRes = await AIConfigurationAPI.runSaveAreaInfo(params);
			pageControlState.saveBtnLoading = false;
			if (res.code === 0) {
				canvasState.isEditCavans = false; // 重置保存后的修改状态
				pageControlState.isEdit = false; // 重置保存后的修改状态
				$message.success('保存成功');
				getByAreaInfo();
				camerasAiTreeRef.value.getTree();

				return 'succeed';
			}
			return 'error';
		} catch (error) {
			console.error(error);
		}
	};

	// 弹窗ok 保存
	const serviceModalOk = async (isChange: boolean, deviceAISrvCustomizeConfig: AiServiceListItem) => {
		let serveObj = serveState.serviceList[serveState.serviceList.findIndex((item) => deviceAISrvCustomizeConfig.id === item.id)];
		pageControlState.isEdit = true;
		if (isChange) {
			serveObj.deviceAISrvCustomizeConfig = deviceAISrvCustomizeConfig;
			serveObj.useDefaultConfig = 0;
		} else {
			serveObj.deviceAISrvCustomizeConfig = null;
			serveObj.useDefaultConfig = 1;
		}
		topControlsState.serviceModalVisible = false;
	};

	return {
		serviceModalOk,
		handleSubmit
	};
};

const { serviceModalOk, handleSubmit } = useSave();
/**
 * ============================================= 组件参数绑定 =============================================
 */
/**
 *  服务列表
 */

const propsState = reactive<any>({
	topControlsState,
	pageControlState,
	serveState,
	areaState,
	canvasState,
	videoLoading: videoLoading.value,
	cameraInfoState
});
/**
 * ============================================= 初始化 和卸载 =============================================
 */

onMounted(async () => {
	ScoketSend({ webPage: 'cameraDeviceConfig', userId: token, stater: 0 });
});

onUnmounted(() => {
	ScoketSend({ webPage: 'cameraDeviceConfig', userId: token, stater: 1 });
	videoStatus(Number(cameraInfoState.cameraId), true);
	play && play.close();
	clearTimeout(timer);
});

/**
 * ============================================= sokcet,路由 监听 =============================================
 */

SocketState.ws.onmessage = async (info: { data: string }) => {
	let obj = JSON.parse(info.data);
	if (obj) {
		if (obj.message === 'SEND_CHECK_VIDEO_MESSAGE') {
			let param = {
				ids: [Number(cameraInfoState.id)],
				inspection: 1
			};
			await realVideoApi.getCheck(param);
		}
	}
};
// 路由守卫
onBeforeRouteLeave((to, _from, next) => {
	if (to.path === '/login') {
		next();
	} else {
		if (pageDataCompare()) {
			next();
		} else {
			confirmState.saveFun = next;
		}
	}
});
</script>

<style lang="less">
.copy-region-modal {
	.cancel-btn {
		display: none;
	}
}

.config-manage-box {
	--cameras-tree-width: 272px; // 摄像头树宽
	--cameras-top-height: 56px; // 摄像头顶部
	--cameras-ai-server-list-width: 300px; // 摄像头顶部
	--cameras-video-top-height: 58px; // 视频顶部

	height: calc(100vh - 124px);
	margin: 24px 16px 0;
	border: 1px solid #20305b;
	border-radius: 8px;
	background: #0b162b;
	backdrop-filter: blur(2px);

	.config-manage-main-core {
		display: flex;
		align-items: center;
		overflow: hidden;
		height: 100%;
		border-radius: 10px 0 0;
		background-color: #21293c;
		flex: 1;

		.config-manage-main-ai-server-list {
			height: 100%;
		}

		.config-manage-main-video {
			overflow: hidden;
			height: 100%;
			border-radius: 8px;
			padding: 0 20px 14px;
			padding-top: 16px;
			background-color: rgba(0, 0, 0, 0.08);
			outline: none;
			flex: 1;

			.config-manage-main-video-main {
				width: 100%;
				height: calc(100% - var(--cameras-video-top-height) - 26px - 14px);
				background-color: #0e1c32;

				.video-play-error {
					display: flex;
					flex-direction: column;
					align-items: center;
					gap: 5px;
				}

				.draw-container {
					position: relative;
					display: flex;
					overflow: auto;
					width: 100%;
					height: 100%;
					background-color: @background02;
					flex: 1;
					flex-direction: column;
					justify-content: center;
					align-items: center;

					.video-srs {
						display: none;
					}

					.video-zlm {
						position: absolute;
						z-index: -1;
						scale: 0.588;
						width: 1920px;
						height: 1080px;
					}

					.video-info {
						position: absolute;
						bottom: 4px;
						left: 8px;
						font-size: 12px;
						line-height: 20px;
						color: #fff;
					}

					.video-empty {
						position: absolute;
						z-index: 1;
						display: flex;
						flex-direction: column;
						justify-content: center;
						width: 100%;
						height: 100%;
						text-align: center;
						color: @text01;
						align-items: center;
						background-color: #0e1c32;
					}
				}
			}
		}
	}

	.config-manage-main {
		display: flex;
		height: calc(100% - var(--cameras-top-height));

		:where(.css-dev-only-do-not-override-1t97qq9).ant-radio-button-wrapper:not(:first-child)::before {
			display: none;
		}
	}
}
</style>
